using System.IO;
using UnityEngine;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Text;

public static class ConfigManager
{
    private const string CONFIG_DIR_PATH = "/Configs/";
    private const string SETTINGS_NAME = "settings.json";
    private const string ROUND_NAME_FORMATE = "round{0}.json";
    private const string RECORDS_NAME = "records.json";

    private static string persistentDataPath;
    private static string streamingAssetsPath;

    private static string PConfigDir;
    private static string PSettings;
    private static string PRecords;
    private static string PRoundxFormat;

    static ConfigManager()
    {
        persistentDataPath = Application.persistentDataPath;
        streamingAssetsPath = Application.streamingAssetsPath;
        PConfigDir = persistentDataPath + CONFIG_DIR_PATH;
        PSettings = PConfigDir + SETTINGS_NAME;
        PRecords = PConfigDir + RECORDS_NAME;
        PRoundxFormat = PConfigDir + ROUND_NAME_FORMATE;

        string sConfigDir = streamingAssetsPath + CONFIG_DIR_PATH;
        string sSettings = sConfigDir + SETTINGS_NAME;
        string sRecords = sConfigDir + RECORDS_NAME;
        string sRoundxFormat = sConfigDir + ROUND_NAME_FORMATE;

        if (!Directory.Exists(PConfigDir))
            Directory.CreateDirectory(PConfigDir);

        if (!File.Exists(PSettings))
            CopyStreamingAssetsToPersistentData(sSettings, PSettings);
        if (!File.Exists(PRecords))
            CopyStreamingAssetsToPersistentData(sRecords, PRecords);
        int roundNum = LoadSettings().RoundNumber;
        for (int i = 0; i < roundNum; ++i)
        {
            if (!File.Exists(string.Format(PRoundxFormat, i)))
                CopyStreamingAssetsToPersistentData(
                    string.Format(sRoundxFormat, i),
                    string.Format(PRoundxFormat, i));
        }
    }

    //将StreamingAssets中的预载配置文件拷贝到PersistentData中, 方便读写
    private static void CopyStreamingAssetsToPersistentData(string sPath, string pPath)
    {
        WWW www = new WWW(sPath);
        // if (www.isDone) { Debug.Log(sPath); }
        // else { Debug.Log(sPath + " Copy OK "); }
        FileStream fs = new FileStream(pPath, FileMode.OpenOrCreate);
        StreamWriter sw = new StreamWriter(fs);
        sw.WriteLine(www.text);
        sw.Close();
        fs.Close();
    }
    private static T LoadConfig<T>(string path) where T : new()
    {
        if (!File.Exists(path))
        {
            File.Create(path);
            File.WriteAllText(path, JsonConvert.SerializeObject(new T()), Encoding.UTF8);
        }
        string json = File.ReadAllText(path, Encoding.UTF8);
        return JsonConvert.DeserializeObject<T>(json);
    }
    private static void SaveConfig<T>(T config, string path)
    {
        string json = JsonConvert.SerializeObject(config);
        File.WriteAllText(path, json, Encoding.UTF8);
    }

    //拷贝后关卡数量信息
    public static int CalculateRoundNumber() { return Directory.GetFileSystemEntries(PConfigDir, "round*.json").Length; }
    public static void SaveSettings(Settings config) { SaveConfig<Settings>(config, PSettings); }
    public static void SaveRecord(Record record)
    {
        List<Record> records = LoadConfig<List<Record>>(PRecords);

        if (records != null)
        {
            int index = record.RoundIndex;
            if (records.Count > index)
            {
                if//更高的纪录
                (
                    record.StarNumber > records[index].StarNumber ||
                    (record.StarNumber == records[index].StarNumber &&
                        (record.Step > records[index].Step || record.Time > records[index].Time)
                    )
                )
                {
                    records[index] = record;
                    TCPClient.Request = new Request(ConfigManager.LoadSettings().Username, Request.ADD_RANKING_REQUEST, index, record);
                    TCPClient.SendRequest();
                }
            }
            else//新关卡记录
            {
                records.Add(record);
                TCPClient.Request = new Request(ConfigManager.LoadSettings().Username, Request.ADD_RANKING_REQUEST, index, record);
                TCPClient.SendRequest();
            }
        }
        else//？
        {
            records = new List<Record>();
            records.Add(record);
            TCPClient.Request = new Request(ConfigManager.LoadSettings().Username, Request.ADD_RANKING_REQUEST, 0, record);
            TCPClient.SendRequest();
        }
        SaveConfig(records, PRecords);
    }
    public static Settings LoadSettings() { return LoadConfig<Settings>(PSettings); }
    public static List<Record> LoadRecords() { return LoadConfig<List<Record>>(PRecords); }
    public static Round LoadRound(int num) { return LoadConfig<Round>(string.Format(PRoundxFormat, num)); }
    public static void ClearRecords() { File.WriteAllText(PRecords, string.Empty, Encoding.UTF8); }
    public static void DownloadRoundsCallBack(string json)
    {
        List<Round> rounds = JsonConvert.DeserializeObject<List<Round>>(json);

        Settings config = LoadConfig<Settings>(PSettings);
        config.RoundNumber = rounds.Count;
        SaveConfig<Settings>(config, PSettings);

        foreach (Round round in rounds)
        {
            string path = string.Format(PRoundxFormat, rounds.IndexOf(round));
            File.Delete(path);
            FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(JsonConvert.SerializeObject(round));
            sw.Close();
            fs.Close();
            // File.WriteAllText(path, JsonConvert.SerializeObject(round), Encoding.UTF8);
        }
    }

}
